#include <iostream>
#include <memory>
#include <thread>

using Resourse = int;

std::shared_ptr<Resourse> CreateResourse() { return std::make_shared<Resourse>(1); }

void User1(std::shared_ptr<Resourse> p) {
  if (p) {
    // 1 使用p
    std::cout << "use p in user1 thread." << "\n";
  }

  std::cout << "User1: use count = " << p.use_count() << "\n";

  return;
}

void User2(std::shared_ptr<Resourse> p) {
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  if (p) {
    // 2 使用p
    std::cout << "use p in user2 thread." << "\n";
  }

  std::cout << "User2: use count = " << p.use_count() << "\n";

  return;
}

int main() {
  std::shared_ptr<Resourse> res = CreateResourse();

  std::cout << "CreateResourse: use count = " << res.use_count() << "\n";

  // 启动线程t1和t2，运行user函数，使用res
  std::thread t1(User1, res);
  std::thread t2(User2, res);

  // 等待线程结束，谁也不需要考虑res资源的释放
  std::cout << "thread t2: use count = " << res.use_count() << "\n";
  t1.join();
  std::cout << "t1.join(): use count = " << res.use_count() << "\n";
  t2.join();
  std::cout << "t2.join(): use count = " << res.use_count() << "\n";

  return 0;
}